(function($){
    
    var _ddActionMenuTmp = [
        '<ul class="ddActionMenu level1">',
            '<% for ( var i = 0; i < menus.length; i++ ) { %>',
                '<li class="ddActionMenuItem <%= getMenuItemClass(menus[i]) + " " + getMenuItemOrderClass(i, menus.length) %>" val="<%=menus[i]["value"]%>" >',
                   '<% var subMenus = menus[i]["subMenus"]; %>',
                   '<% if( subMenus && subMenus.data && subMenus.data.length ) { %>',                          
                       '<div class="hasSubMenu"><%= menus[i]["text"] %></div>',
                       '<ul class="ddActionMenu level2" style="width:<%= subMenus["width"] %>">',
                           '<% for ( var j = 0; j < subMenus.data.length; j++ ) { %>',
                               '<li class="ddActionMenuItem <%= getMenuItemClass(subMenus.data[j]) + " " + getMenuItemOrderClass(j, subMenus.data.length) %> ',
                                   'val="<%=subMenus.data[j]["value"]%>" ',
                                   '<% if(subMenus.data[j].attrs){ %>',
                                       '<% for( var attr in subMenus.data[j].attrs ){ %>',
                                            '<%=attr%>', '=', '"', '<%= subMenus.data[j].attrs[attr] %>', '" ',
                                       '<% } %>',
                                   '<% } %>',
                               '>',                                    
                                   '<%= subMenus.data[j]["text"] %>',
                               '</li>',
                           '<% } %>',
                       '</ul>',
                   '<% } else { %>',
                       '<%= menus[i]["text"] %>',
                   '<% } %>',
                '</li>',
            '<% } %>',
        '</ul>'
    ].join('');
    
    /**
     * 默认配置.
     */
    var _defaultConfig = {
        onClick : function(){},
        width : 50,
        menuAlign : 'left'
    };
    
    /**
     * config : {
     *		data : [
     * 			{text : 'aaa', value : 0 },
     * 			{text : 'bbb', value : 1 },
     *          {text : 'ccc', value : 2, subMenus : {
     *              data : [ ... ],
     *              onClick : function(value, text, index){}
     *          } },
     * 		],
     * 		onClick : function(value, text, index){}
     * }
     */
    $.fn.ddActionMenu = function(config) {
        config = $.extend({}, _defaultConfig, config);                
	    var $self = $(this).first().addClass('ddActionMenuCtn').addClass(config['theme']);		
		//去掉默认的title提示，否则其可能会遮盖下拉菜单，影响用户体验。		
	    $self.removeAttr('title');		
		
		if(Type.isString(config['data'])){
		    //兼容Data格式如:'Create Chat Group|chatGroup,Share Link|shareLink,Create Event|chatEvent,User Manage|userMng,Create Survey|survey',
		    var dataStrArr = config['data'].split(',');
		    config['data'] = [];
		    for(var i=0; i<dataStrArr.length; i++){
		        var dataItemArr = dataStrArr[i].split('|');
		        config['data'].push({
		            text : dataItemArr[0],
		            value : dataItemArr[1]
		        });
		    }		    
		}
		
		var $arrowRightBottom = $('<arrow class="arrowRightBottom"></arrow>'),
			$ddActionMenu = $(tmpl(_ddActionMenuTmp, { 
			    menus : config['data'],
			    getMenuItemClass : function(itemCfg){
			        var cls = [];
			        if(itemCfg['checked']){ cls.push('checked'); }
			        if(itemCfg['type']){ cls.push(itemCfg['type']); }
			        return cls.join(' ');
			    },
			    getMenuItemOrderClass : function(index, count){
			        var cls = [];
			        if(index == 0){ cls.push('first'); }
			        if(index == count - 1){ cls.push('last'); }
			        return cls.join(' ');
			    } 
		    }));
		
		$self.append($arrowRightBottom).append($ddActionMenu);	
				
	    $ddActionMenu.css('min-width', config['width']);		
		
		if(config['menuAlign'] === 'right'){
		    $ddActionMenu.addClass('ddActionRightMenu');
		}
				
		//on click 触发
		if(config['triggerType'] === 'click'){   
		    $self.bind({
                'click' : function(e){
                    //关闭同页面的其它下拉菜单。
                    $('.ddActionMenu').not($ddActionMenu).hide();
                    //交替展示下拉菜单。
                    $ddActionMenu.toggle();
                    return false;
                }
            });
            $ddActionMenu.hideOnClickDoc();
		} 
		//on mouseover 触发
		else {  
    		$self.bind({
    		    'mouseover' : function(){ $ddActionMenu.show(); },
                'mouseout' : function(){ $ddActionMenu.hide(); }
    		});
        }
		
		$ddActionMenu.find('li').click(function(e){
		    var $menuItem = $(this); 
		    if(!$menuItem.hasClass('disabled')){
		        //radio button menu item.
		        if($menuItem.hasClass('radio')){
		            if($menuItem.hasClass('checked')){
		                return $ddActionMenu.hide();
		            } else {
		                $menuItem.addClass('checked').siblings().removeClass('checked');
		            }
		        }	
		        //checkbox menu item.
		        if($menuItem.hasClass('checkbox')){
                    $menuItem.toggleClass('checked');
                } 
			    config['onClick'].call( $self, $menuItem.attr('val'), $menuItem.text(), $menuItem.index(), !!$menuItem.hasClass('checked'), $menuItem );    		     
    		}
    		$ddActionMenu.hide();
		    e.stopPropagation();
		});		
		//使菜单容器也响应点击事件。
		if(config['isCtnResponsive'] && config['triggerType'] != 'click'){		
	        $self.bind('click', function(e){		    
                $ddActionMenu.find('li:first').trigger('click');
                return false;
            });
        } 
		$ddActionMenu.find('.ddActionMenuItem').bind({
		    'mouseover' : function(){
		        var $subMenu = $(this).find('.ddActionMenu');
		        if($subMenu){
		            $subMenu.css('top', '0px').css('left', ( $(this).parent().width() ) + 'px').show();
		        }
		    },
		    'mouseout' : function(){
		        $(this).find('.ddActionMenu').hide();
		    }
		});				
		return $self;
	};		    
})(jQuery);